const http = require('http');
const fs = require('fs');
const path = require('path');

const port = 8081;
const args = process.argv.slice(2);
const fileName = args[0] || __filename;

const server = http.createServer((req, res) => {
  fs.open(fileName, 'r', (err, fd) => {
    if (err) {
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.end("\u6587\u4ef6 " + fileName + " \u4e0d\u5b58\u5728");
      console.error("\u6587\u4ef6 " + fileName + " \u4e0d\u5b58\u5728");
      return;
    }

    const stats = fs.fstatSync(fd);
    const buffer = Buffer.alloc(stats.size);
    
    fs.read(fd, buffer, 0, buffer.length, null, (err) => {
      if (err) {
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('\u8bfb\u53d6\u6587\u4ef6\u51fa\u9519');
        console.error('\u8bfb\u53d6\u6587\u4ef6\u51fa\u9519:', err);
        return;
      }

      fs.close(fd, (err) => { 
        if (err) console.error('\u5173\u95ed\u6587\u4ef6\u51fa\u9519:', err);
      });

      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end(buffer.toString());
      console.log("\u6210\u529f\u8bfb\u53d6\u5e76\u8fd4\u56de " + fileName + " \u5185\u5bb9");
    });
  });
});

server.listen(port, () => {
  console.log("\u670d\u52a1\u5668\u8fd0\u884c\u5728 http://localhost:" + port);
  console.log("\u5c1d\u8bd5\u8bbf\u95ee\u6587\u4ef6: " + fileName);
});